<template>
  <div class="document-code-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>单据编码规则管理</h2>
    </div>

    <!-- 搜索与操作区 -->
    <div class="search-operation-bar">
      <el-form :model="searchForm" inline label-width="80px">
        <el-form-item label="业务实体">
          <el-select v-model="searchForm.businessEntity" placeholder="全部" clearable>
            <el-option label="全部" value="" />
            <el-option
              v-for="item in businessOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="规则名称">
          <el-input
            v-model="searchForm.ruleName"
            placeholder="请输入规则名称"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="operation-buttons">
        <el-button type="primary" icon="Plus" @click="handleAdd">
          新建规则
        </el-button>
      </div>
    </div>

    <!-- 数据列表 -->
    <div class="table-container">
      <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="businessEntity" label="业务实体" width="160" align="center" />
        <el-table-column prop="ruleName" label="规则名称" width="160" align="center" />
        <el-table-column prop="entityField" label="单据字段" width="140" align="center" />
        <el-table-column prop="dateField" label="日期排序字段" width="160" align="center" />
        <el-table-column prop="prefix" label="前缀" width="100" align="center" />
        <el-table-column prop="ruleType" label="规则类型" width="120" align="center" />
        <el-table-column prop="numberDigits" label="编号位数" width="100" align="center" />
        <el-table-column prop="growthType" label="增长类型" width="140" align="center" />
        <el-table-column prop="codePreview" label="编码预览" min-width="180" align="center" />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" link icon="Edit" @click="handleEdit(scope.row)" size="small">
              编辑
            </el-button>
            <el-button type="danger" link icon="Delete" @click="handleDelete(scope.row.id)" size="small">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新建/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :before-close="handleDialogClose"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="120px"
        class="dialog-form"
      >
        <el-form-item label="业务实体" prop="businessEntity">
          <el-select v-model="form.businessEntity" placeholder="请选择业务实体" style="width: 100%">
            <el-option
              v-for="item in businessOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="form.ruleName" placeholder="请输入规则名称" />
        </el-form-item>

        <el-form-item label="单据字段" prop="entityField">
          <el-input v-model="form.entityField" placeholder="如：ProduceCode（关联实体字段）" />
        </el-form-item>

        <el-form-item label="日期排序字段" prop="dateField">
          <el-input v-model="form.dateField" placeholder="如：CreateTime（排序用日期字段）" />
        </el-form-item>

        <el-form-item label="前缀" prop="prefix">
          <el-input v-model="form.prefix" placeholder="如：QI（质检单）、PO（采购单）" />
        </el-form-item>

        <el-form-item label="规则类型" prop="ruleType">
          <el-radio-group v-model="form.ruleType" style="width: 100%; display: flex; gap: 20px;">
            <el-radio label="年">年（如：2024）</el-radio>
            <el-radio label="年月">年月（如：202409）</el-radio>
            <el-radio label="年月日">年月日（如：20240926）</el-radio>
            <el-radio label="无">无（不包含日期）</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="编号位数" prop="numberDigits">
          <el-input-number
            v-model="form.numberDigits"
            :min="1"
            :max="10"
            controls-position="right"
            placeholder="编号的位数（补零）"
          />
        </el-form-item>

        <el-form-item label="增长类型" prop="growthType">
          <el-select v-model="form.growthType" placeholder="请选择编号增长方式" style="width: 100%">
            <el-option label="每天从1开始" value="每天从1开始" />
            <el-option label="累计自增" value="累计自增" />
          </el-select>
        </el-form-item>

        <el-form-item label="连接符号">
          <el-input v-model="form.connector" placeholder="如：-、_（连接各部分的符号，可选）" />
        </el-form-item>

        <el-form-item label="编码预览">
          <el-tag type="info" style="font-size: 16px; padding: 10px; width: 100%; text-align: center;">
            {{ previewCode }}
          </el-tag>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 接口基础路径（使用分页正常的 /api/Accounts）
const baseUrl = 'http://localhost:5046/api/Accounts'

// 响应式数据
const loading = ref(false) // 列表加载状态
const submitting = ref(false) // 表单提交状态
const dialogVisible = ref(false) // 弹窗显示状态
const formRef = ref(null) // 表单引用
const tableData = ref([]) // 表格数据
const currentOperation = ref('add') // 当前操作（add/edit）
const currentEditId = ref(null) // 当前编辑的ID

// 搜索表单数据
const searchForm = reactive({
  businessEntity: '',
  ruleName: ''
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表单数据（与后端接口字段匹配）
const form = reactive({
  businessEntity: '',
  ruleName: '',
  entityField: '',
  dateField: '',
  prefix: '',
  ruleType: '年月日',
  numberDigits: 3,
  growthType: '每天从1开始',
  connector: '-'
})

// 表单验证规则（修复numberDigits验证）
const rules = {
  businessEntity: [{ required: true, message: '请选择业务实体', trigger: 'change' }],
  ruleName: [
    { required: true, message: '请输入规则名称', trigger: 'blur' },
    { max: 50, message: '规则名称不能超过50个字符', trigger: 'blur' }
  ],
  entityField: [
    { required: true, message: '请输入单据字段', trigger: 'blur' },
    { max: 50, message: '单据字段不能超过50个字符', trigger: 'blur' }
  ],
  dateField: [
    { required: true, message: '请输入日期排序字段', trigger: 'blur' },
    { max: 50, message: '日期排序字段不能超过50个字符', trigger: 'blur' }
  ],
  prefix: [
    { required: true, message: '请输入前缀', trigger: 'blur' },
    { max: 20, message: '前缀不能超过20个字符', trigger: 'blur' }
  ],
  ruleType: [{ required: true, message: '请选择规则类型', trigger: 'change' }],
  numberDigits: [
    { required: true, message: '请设置编号位数', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (typeof value !== 'number' || isNaN(value)) {
          return callback(new Error('编号位数必须是数字'));
        }
        if (value < 1 || value > 10) {
          return callback(new Error('编号位数需在1-10之间'));
        }
        callback();
      },
      trigger: 'change'
    }
  ],
  growthType: [{ required: true, message: '请选择增长类型', trigger: 'change' }]
};

// 业务实体选项
const businessOptions = ref([
  { label: '质检单', value: 'QualityInspection' },
  { label: '生产工单', value: 'ProductionOrder' },
  { label: '采购单', value: 'PurchaseOrder' },
  { label: '工艺流程', value: 'ProcessFlowModel' }
])

// 编码预览计算属性
const previewCode = computed(() => {
  const { prefix, ruleType, numberDigits, connector } = form
  if (!prefix.trim()) return '请先填写「前缀」以生成预览'

  const now = new Date()
  let datePart = ''
  switch (ruleType) {
    case '年': datePart = now.getFullYear().toString(); break
    case '年月': datePart = `${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}`; break
    case '年月日': datePart = `${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}`; break
    case '无': datePart = ''; break
  }

  const numberPart = '1'.padStart(numberDigits, '0')
  const connectorStr = connector.trim() || ''
  const parts = []
  if (prefix) parts.push(prefix)
  if (datePart) parts.push(datePart)
  if (numberPart) parts.push(numberPart)
  return parts.join(connectorStr)
})

// 弹窗标题
const dialogTitle = computed(() => {
  return currentOperation.value === 'add' ? '新建单据编码规则' : '编辑单据编码规则'
})

// 获取规则列表
const getDocumentCodeRules = async () => {
  loading.value = true
  try {
    const params = {
      BusinessEntity: searchForm.businessEntity,
      RuleName: searchForm.ruleName,
      PageIndex: pagination.currentPage,
      PageSize: pagination.pageSize
    }
    const response = await axios.get(`${baseUrl}/GetList`, { params })
    if (response.data.code === 200) {
      tableData.value = response.data.totalPage || []
      pagination.total = response.data.totalcount || 0
    } else {
      ElMessage.error(response.data.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取列表错误:', error)
    ElMessage.error('获取数据失败，请检查网络或接口')
  } finally {
    loading.value = false
  }
}

// 新建规则
const createDocumentCodeRule = async () => {
  submitting.value = true
  try {
    const response = await axios.post(`${baseUrl}/Create`, form)
    if (response.data.code === 200) {
      ElMessage.success('创建成功！')
      dialogVisible.value = false
      getDocumentCodeRules()
    } else {
      ElMessage.error(response.data.message || '创建失败')
    }
  } catch (error) {
    console.error('创建错误:', error)
    ElMessage.error('创建失败，请检查接口')
  } finally {
    submitting.value = false
  }
}

// 编辑规则
const updateDocumentCodeRule = async () => {
  submitting.value = true
  try {
    const response = await axios.put(`${baseUrl}/Update/${currentEditId.value}`, form)
    if (response.data.code === 200) {
      ElMessage.success('更新成功！')
      dialogVisible.value = false
      getDocumentCodeRules()
    } else {
      ElMessage.error(response.data.message || '更新失败')
    }
  } catch (error) {
    console.error('更新错误:', error)
    ElMessage.error('更新失败，请检查接口')
  } finally {
    submitting.value = false
  }
}

// 删除规则
const deleteDocumentCodeRule = async (id) => {
  try {
    await ElMessageBox.confirm('确定删除？删除后无法恢复！', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'danger'
    })
    const response = await axios.delete(`${baseUrl}/Delete/${id}`)
    if (response.data.code === 200) {
      ElMessage.success('删除成功！')
      getDocumentCodeRules()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error.name !== 'MessageBoxCancel') {
      console.error('删除错误:', error)
      ElMessage.error('删除失败，请检查接口')
    }
  }
}

// 搜索事件处理
const handleSearch = () => {
  pagination.currentPage = 1
  getDocumentCodeRules()
}

// 重置事件处理
const handleReset = () => {
  searchForm.businessEntity = ''
  searchForm.ruleName = ''
  pagination.currentPage = 1
  getDocumentCodeRules()
}

// 分页大小变化处理
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  getDocumentCodeRules()
}

// 页码变化处理
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  getDocumentCodeRules()
}

// 新建按钮点击事件
const handleAdd = () => {
  currentOperation.value = 'add'
  currentEditId.value = null
  Object.assign(form, {
    businessEntity: '',
    ruleName: '',
    entityField: '',
    dateField: '',
    prefix: '',
    ruleType: '年月日',
    numberDigits: 3,
    growthType: '每天从1开始',
    connector: '-'
  })
  if (formRef.value) formRef.value.clearValidate()
  dialogVisible.value = true
}

// 编辑按钮点击事件
const handleEdit = (row) => {
  currentOperation.value = 'edit'
  currentEditId.value = row.id
  Object.assign(form, {
    businessEntity: row.businessEntity,
    ruleName: row.ruleName,
    entityField: row.entityField,
    dateField: row.dateField,
    prefix: row.prefix,
    ruleType: row.ruleType || '年月日',
    numberDigits: row.numberDigits || 3,
    growthType: row.growthType || '每天从1开始',
    connector: row.connector || '-'
  })
  if (formRef.value) formRef.value.clearValidate()
  dialogVisible.value = true
}

// 删除按钮点击事件
const handleDelete = (id) => {
  deleteDocumentCodeRule(id)
}

// 弹窗关闭事件
const handleDialogClose = () => {
  if (formRef.value) formRef.value.clearValidate()
  dialogVisible.value = false
}

// 表单提交事件
const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    currentOperation.value === 'add' ? await createDocumentCodeRule() : await updateDocumentCodeRule()
  } catch (error) {
    console.log('提交失败:', error)
  }
}

// 页面加载时获取列表数据
onMounted(() => {
  getDocumentCodeRules()
})
</script>

<style scoped>
.document-code-container {
  padding: 20px;
  background: #fff;
  min-height: calc(100vh - 84px);
}

.page-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee; 
}

.search-operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.operation-buttons {
  display: flex;
  gap: 10px;
  margin-top: 5px;
}

.table-container {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-form {
  margin-top: 10px;
}

.el-radio-group {
  flex-wrap: wrap;
}
</style>
